package qiniufile

import (
	"context"
	"net/http"
	"os"

	"mall/service/backend/api/internal/logic/media/qiniufile"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/errorx"

	"github.com/zeromicro/go-zero/rest/httpx"
)

func DownloadFileHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := context.WithValue(r.Context(), "lang", r.Header.Get("Accept-Language"))
		var req types.UUIDPathReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(ctx, w, err)
			return
		}

		if errMsg := svcCtx.Validator.Validate(&req, r.Header.Get("Accept-Language")); errMsg != "" {
			httpx.ErrorCtx(ctx, w, errorx.NewCodeError(svcCtx.Validator.ErrorCode, errMsg))
			return
		}

		l := qiniufile.NewDownloadFileLogic(ctx, svcCtx)
		filePath, err := l.DownloadFile(&req)
		if err != nil {
			err = svcCtx.Trans.TransError(ctx, err)
			httpx.ErrorCtx(ctx, w, err)
		} else {
			body, err := os.ReadFile(filePath)
			if err != nil {
				httpx.Error(w, errorx.NewApiError(http.StatusInternalServerError, err.Error()))
				return
			}
			w.Header().Set("Accept-Encoding", "identity;q=1, *;q=0")
			w.Write(body)
		}
	}
}
